const jwt = require('jsonwebtoken');

exports.authenticate = (req, res, next) => {
  const authHeader = req.headers.authorization;

  // 验证认证头格式
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(403).json({
      code: 403,
      message: 'Authorization header格式错误'
    });
  }

  // 提取并验证token
  const token = authHeader.split(' ')[1];
  if (!token || token.length < 50) {
    return res.status(403).json({
      code: 403,
      message: '无效的访问令牌'
    });
  }

  // JWT验证逻辑
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.userId = decoded.userId;
    next();
  } catch (err) {
    const message = err.name === 'TokenExpiredError' 
      ? 'Token已过期' 
      : '无效Token';
    return res.status(403).json({ 
      code: 403,
      message
    });
  }
};
